package com.zmn.oms.admin.controller.work.list;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.coa.common.dio.OrderAmountForBackDIO;
import com.zmn.coa.common.dio.ProductInfoDIO;
import com.zmn.coa.common.dro.OrderAmountForBackDRO;
import com.zmn.coa.dubbo.impl.interfaces.order.background.BackOrderAmountRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.consts.GlobalConsts;
import com.zmn.dms.common.dio.order.AdvanceBatchInfoDIO;
import com.zmn.dms.common.dto.order.dro.AdvanceBatchInfoDRO;
import com.zmn.dms.common.dto.preferential.dro.PromBaseRuleDRO;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.dms.common.query.order.OrderCoupPromQuery;
import com.zmn.oms.admin.controller.work.WorkBaseController;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountCalcBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.common.constant.DiscountConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.TriggerAmountChangeEnum;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.WorkAmountUtil;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.orderamount.OrderAmountCalcBO;
import com.zmn.oms.model.bo.orderamount.ReCalcOrderAmountDIO;
import com.zmn.oms.model.dto.discount.NewOrderDiscountDTO;
import com.zmn.oms.model.dto.work.discount.OrderWorkDiscountQuery;
import com.zmn.oms.model.dto.work.modify.CheckQuotationTypeOrderDTO;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.dto.work.discount.OrderWorkDiscountURLQuery;
import com.zmn.oms.model.vo.discount.AddOrderDiscountVO;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.uuc.common.dro.user.UserBaseDRO;
import com.zmn.uuc.common.query.user.UserMobilePlatQuery;
import com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService;
import com.zmn.vas.common.dro.member.VerifyMemberDRO;
import com.zmn.vas.dubbo.interfaces.member.MemberModifyRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sunlife
 * @date:2022/4/18 下午4:04
 * description:
 */
@Controller
@RequestMapping("/work")
@Slf4j
public class WorkDiscountListController extends WorkBaseController {

    @Autowired
    protected ServItemBService servItemBService;
    @Autowired
    protected OrderDiscountService orderDiscountService;
    @Autowired
    protected OrderAmountCalcBService orderAmountCalcBService;
    @Autowired
    protected OrderProductService orderProductService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    MemberModifyRemoteService memberModifyRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    ProductForeignListRemoteService productForeignListRemoteService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    BackOrderAmountRemoteService backOrderAmountRemoteService;
    @DubboReference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    UserListRemoteService userListRemoteService;

    private static final String DISCOUNT_BASE_URL = "/order/coupProm/list.action";

    /**
     * 查询优惠券信息 下单
     */
    @RequestMapping(value = "/addOrder/getDiscountURL")
    @ResponseBody
    public ResultDTO getAddOrderDiscountURL(OrderWorkDiscountURLQuery query) {

        OrderCoupPromQuery discountQuery = new OrderCoupPromQuery();
        // 下单页跳转
        discountQuery.setJumpPageFlg(GlobalConsts.NO);
        discountQuery.setChannelId(query.getChannelId());
        discountQuery.setCityId(query.getCityId());
        discountQuery.setBizType(Optional.ofNullable(query.getBizType()).orElse(GlobalConsts.BIZ_TYPE_C));
        discountQuery.setUserId(String.valueOf(query.getUserId()));
        discountQuery.setOrderDateTime(DateUtil.getNowFormatted());
        discountQuery.setPrice(query.getPrice());
        discountQuery.setCancelOrNot(false);

        if (StringUtil.isNotBlank(query.getTelephone()) && Objects.equals(query.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CC)) {
            UserMobilePlatQuery userQuery = new UserMobilePlatQuery();

            userQuery.setMobile(query.getTelephone());
            userQuery.setPlat(query.getPlat());

            log.info("获取手机号对应的用户 入参：{}", JSON.toJSONString(userQuery));
            ResponseDTO<UserBaseDRO> userResponseDTO = userListRemoteService.getMajorUserByMobileAndPlat(userQuery);
            log.info("获取手机号对应的用户 出参：{}", JSON.toJSONString(userResponseDTO));
            if (userResponseDTO.isSuccess() && Objects.nonNull(userResponseDTO.getData())) {
                discountQuery.setUserId(String.valueOf(userResponseDTO.getData().getUserId()));
            }
        }

        if (StringUtil.isNotBlank(discountQuery.getUserId()) && NumberUtil.isNotNullOrZero(query.getPrice())) {
            OrderWorkDiscountQuery bestDiscountQuery = BeanMapper.map(query, OrderWorkDiscountQuery.class);
            bestDiscountQuery.setUserId(Long.valueOf(discountQuery.getUserId()));
            try {
                OrderAmountForBackDRO backDRO = this.getBestDiscountByQuery(bestDiscountQuery);
                // 最佳优惠组合
                if (CollectionUtils.isNotEmpty(backDRO.getCurrentPromLink())) {
                    List<String> codeList = backDRO.getCurrentPromLink().stream()
                            .filter(item ->  StringUtil.isNotBlank(item.getCode()) && !item.getCode().startsWith("ADVANCE-COUPON"))
                            .map(PromBaseRuleDRO::getCode).collect(Collectors.toList());
                    discountQuery.setCouponCodes(codeList);
                }
            } catch (OmsBaseException e) {
                log.error("获取订单优惠失败");
            }
        }

        // 处理产品信息
        Integer showProductId = null;
        if (!Objects.equals(query.getShowType(), 2)) {
            // 获取对应的前台产品ID
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(query.getProductId()));
            defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            defaultEcProductQuery.setChannelId(query.getChannelId());
            defaultEcProductQuery.setBizType(query.getBizType());
            defaultEcProductQuery.setCityId(query.getCityId());
            ResponseDTO<List<ProductBaseDRO>> responseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            if (!CollectionUtils.isEmpty(responseDTO.getData())) {
              showProductId = responseDTO.getData().get(0).getProductId();
            } else {
                return ResultDTO.fail(String.format("后端产品[%s]未找到前端产品", query.getProductId()));
            }
        } else {
            showProductId = query.getProductId();
        }
        discountQuery.setProductId(showProductId);

        Integer servItemType = query.getServItemType();
        if (NumberUtil.isNullOrZero(query.getServItemType())) {
            // 检查工单服务类型
            CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = CheckQuotationTypeOrderDTO
                    .builder()
                    .bizType(query.getBizType())
                    .channelId(query.getChannelId())
                    .cityId(query.getCityId())
                    .platWork(query.getPlat())
                    .productId(query.getProductId())
                    .sourceType(OrderConsts.ORDER_SOURCE_TYPE_NORMAL)
                    .type(query.getType())
                    .build();
            servItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO);
        }
        int tariff = (Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_FAULT) || Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) ? GlobalConsts.YES : GlobalConsts.NO;
        discountQuery.setTariffOnoff(tariff);
        discountQuery.setUntariffOnoff(tariff == GlobalConsts.YES ? GlobalConsts.NO : GlobalConsts.YES);

        if (Objects.isNull(query.getUserId())) {
            discountQuery.setExtendedWarranty(GlobalConsts.NO);
            discountQuery.setUnExtendedWarranty(GlobalConsts.YES);
        } else {
            // 判断是否是会员
            ResponseDTO<VerifyMemberDRO> memberResponseDTO = memberModifyRemoteService.verifyIsMember(query.getUserId());
            logger.info("获取用户信息 入参：{}, 出参：{}", query.getUserId(), JSON.toJSONString(memberResponseDTO));
            if (memberResponseDTO.isSuccess()) {
                int extendedWarranty = memberResponseDTO.getData().getIsMember() ? GlobalConsts.YES : GlobalConsts.NO;
                discountQuery.setExtendedWarranty(extendedWarranty);
                discountQuery.setUnExtendedWarranty(Objects.equals(extendedWarranty, GlobalConsts.YES) ? GlobalConsts.NO : GlobalConsts.YES);
            }
        }

        return ResultDTO.success(this.convertClassToGetURL(DISCOUNT_BASE_URL, discountQuery));
    }

    /**
     * 查询优惠券信息 下单
     */
    @RequestMapping(value = "/addOrder/getDiscountDetail")
    @ResponseBody
    public ResultDTO getDiscountDetail(OrderWorkDiscountQuery query) {

        if (StringUtil.isNotBlank(query.getTelephone()) && Objects.equals(query.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CC)) {
            UserMobilePlatQuery userQuery = new UserMobilePlatQuery();

            userQuery.setMobile(query.getTelephone());
            userQuery.setPlat(query.getPlat());

            log.info("获取手机号对应的用户 入参：{}", JSON.toJSONString(userQuery));
            ResponseDTO<UserBaseDRO> userResponseDTO = userListRemoteService.getMajorUserByMobileAndPlat(userQuery);
            log.info("获取手机号对应的用户 出参：{}", JSON.toJSONString(userResponseDTO));
            if (userResponseDTO.isSuccess() && Objects.nonNull(userResponseDTO.getData())) {
                query.setUserId(userResponseDTO.getData().getUserId());
            }
        }

        OrderAmountForBackDRO backDRO = null;
        try {
            backDRO = this.getBestDiscountByQuery(query);
        } catch (OmsBaseException e) {
            return ResultDTO.fail(e.getMessage());
        }

        AddOrderDiscountVO discountVO = BeanMapper.map(backDRO, AddOrderDiscountVO.class);

        if (CollectionUtils.isNotEmpty(backDRO.getBestPromLink())) {
            List<NewOrderDiscountDTO> discountList = Lists.newArrayListWithCapacity(backDRO.getBestPromLink().size());

            for (PromBaseRuleDRO promBaseRuleDRO : backDRO.getBestPromLink()) {
                if (StringUtil.isNotBlank(promBaseRuleDRO.getCode()) && promBaseRuleDRO.getCode().startsWith("ADVANCE-COUPON")) {
                    NewOrderDiscountDTO baseDiscount = BeanMapper.map(promBaseRuleDRO, NewOrderDiscountDTO.class);
                    // 获取相关字段 由于DMS与COA实现原因，部分数据放在code中返回
                    // code "ADVANCE-COUPON-[{\"activityId\":3333333,\"activityType\":2,\"batchId\":20291,\"scenarioId\":555}]"
                    NewOrderDiscountDTO tempDiscount = JSON.parseObject(promBaseRuleDRO.getCode().substring(15), NewOrderDiscountDTO.class);
                    BeanMapper.copy(tempDiscount, baseDiscount);

                    discountList.add(baseDiscount);
                }
            }
            discountVO.setBestDiscountList(discountList);
        }

        return ResultDTO.success(discountVO);
    }

    /**
     * 查询优惠券信息 详情
     */
    @RequestMapping(value = "/detail/getDiscountURL")
    @ResponseBody
    public ResultDTO getOrderDetailDiscountURL(Long orderId, Long workId) {
        Assert.notNull(orderId, "订单ID不能为空");
        Assert.notNull(workId, "工单ID不能为空");

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (orderWork == null) {
            return ResultDTO.fail("工单不存在");
        }

        OrderCoupPromQuery discountQuery = new OrderCoupPromQuery();
        // 下单页跳转
        discountQuery.setOrderId(String.valueOf(orderId));
        discountQuery.setJumpPageFlg(GlobalConsts.YES);
        discountQuery.setChannelId(orderWork.getChannelId());
        discountQuery.setCityId(orderWork.getCityId());
        discountQuery.setProductId(orderWork.getShowProductId());
        discountQuery.setBizType(Optional.ofNullable(orderWork.getBizType()).orElse(GlobalConsts.BIZ_TYPE_C));
        discountQuery.setPrice(orderWork.getOriginalAmount());

        discountQuery.setUserId(String.valueOf(orderWork.getUserId()));
        if (NumberUtil.isNotNullOrZero(orderWork.getVisitUserId())) {
            discountQuery.setScanUserId(String.valueOf(orderWork.getVisitUserId()));
        }
        if (Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            discountQuery.setOrderDateTime(DateUtil.getNowFormatted());
        } else {
            discountQuery.setOrderDateTime(DateUtil.toString(orderWork.getReceiveTime()));
        }

        if (Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DISCARD)
                || Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_FAIL)) {
            discountQuery.setCancelOrNot(true);
        } else {
            discountQuery.setCancelOrNot(false);
        }

        discountQuery.setPrice(orderWork.getOriginalAmount());
        discountQuery.setOrderStatus(orderWork.getStatus());

        Integer factAmount = WorkAmountUtil.getWorkFactAmount(orderWork);
        if (Objects.equals(factAmount, orderWork.getTotalAmount())) {
            discountQuery.setOrderPayFlg(true);
        } else {
            discountQuery.setOrderPayFlg(false);
        }

        // 检查工单服务类型
        int tariff = (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FAULT) || Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) ? GlobalConsts.YES : GlobalConsts.NO;
        discountQuery.setTariffOnoff(tariff);
        discountQuery.setUntariffOnoff(tariff == GlobalConsts.YES ? GlobalConsts.NO : GlobalConsts.YES);

        int extendedWarranty = orderWork.getMember() != null ? orderWork.getMember() : GlobalConsts.NO;
        discountQuery.setExtendedWarranty(extendedWarranty);
        discountQuery.setUnExtendedWarranty(Objects.equals(extendedWarranty, GlobalConsts.YES) ? GlobalConsts.NO : GlobalConsts.YES);

        // 获取工单已经使用的优惠券
        List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderId);
        List<String> codeList = orderDiscountList.stream()
                .filter(discount -> Objects.equals(discount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_COMMON.getSubType())
                        || Objects.equals(discount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_VOUCHER.getSubType())
                        || Objects.equals(discount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_CASH.getSubType()))
                .map(OrderDiscount::getItemCode)
                .collect(Collectors.toList());
        discountQuery.setCouponCodesUsed(codeList);

        // 获取当前最佳优惠

        // 没有口碑券 请求
        boolean existKBDiscount = Optional.ofNullable(orderDiscountList).orElse(Collections.emptyList()).stream().anyMatch(e -> Objects.equals(e.getThirdCode(), GlobalConsts.YES));
        if (!existKBDiscount) {
            try {
                OrderAmountForBackDRO orderAmountForBackDRO = this.getBestDiscount(orderWork, codeList);
                if (CollectionUtils.isNotEmpty(orderAmountForBackDRO.getCurrentPromLink())) {
                    List<String> bestCodeList = orderAmountForBackDRO.getCurrentPromLink().stream().map(PromBaseRuleDRO::getCode).collect(Collectors.toList());
                    discountQuery.setCouponCodes(bestCodeList);
                }
            } catch (OmsBaseException e) {
                log.error("获取订单优惠失败", e);
            }
        } else {
            log.info("订单有口碑券，不请求最大优惠");
        }

        return ResultDTO.success(this.convertClassToGetURL(DISCOUNT_BASE_URL, discountQuery));

    }

    private String convertClassToGetURL(String baseUrl, Object param) {
        if (StringUtil.isBlank(baseUrl) || Objects.isNull(param)) {
            return baseUrl;
        }

        // 获取属性
        Field[] fields = param.getClass().getDeclaredFields();
        if (fields.length == 0) {
            return baseUrl;
        }

        // 组装URL
        StringBuilder sb = new StringBuilder(baseUrl).append("?");

        // 遍历属性
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];

            String fieldValue = getFieldFormattedValue(field, param);
            if (StringUtil.isBlank(fieldValue)) {
                continue;
            }
            sb.append(field.getName())
                    .append("=")
                    .append(fieldValue);
            sb.append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    private String getFieldFormattedValue(Field field, Object o) {
        if (Objects.isNull(field)) {
            return null;
        }

        try {
            field.setAccessible(true);

            if (Objects.isNull(field.get(o))) {
                return null;
            }

            if (Objects.equals(field.getType(), Long.class) || Objects.equals(field.getType(), long.class)) {
                // 长整型 防止精度丢失
                return String.format("\'%s\'", field.get(o));
            } else if (Objects.equals(field.getType(), Date.class)) {
                return String.format("\'%s\'", DateUtil.toString((Date) field.get(o)));
            } else if (Objects.equals(field.getType(), List.class)) {
//                ParameterizedType parameterizedType = (ParameterizedType)field.getGenericType();
                // list类型转化为 A，B，C
                List valueList = (List) field.get(o);
                if (CollectionUtils.isEmpty(valueList)) {
                    return null;
                }
                StringBuilder sb = new StringBuilder();
                for (Object value : valueList) {
                    if (value instanceof String) {
                        sb.append(value).append(",");
                    } else {
                        sb.append(String.format("%s", value)).append(",");
                    }
                }

                if (sb.length() >= 1) {
                    return sb.deleteCharAt(sb.length() - 1).toString();
                } else {
                    return null;
                }
            }
            Object fieldValue = field.get(o);
            if (Objects.isNull(fieldValue) || Objects.equals(fieldValue, "null")) {
                return "";
            } else {
                return fieldValue.toString();
            }
        } catch (IllegalAccessException e) {
            log.info("反射错误：field: {}, class:{}, 错误:{}", field.getName(), JSON.toJSONString(o), e.getMessage());
            return null;
        }
    }

    private OrderAmountForBackDRO getBestDiscount(OrderWork orderWork, List<String> codeList) throws OmsBaseException {
        OrderAmountForBackDIO dio = new OrderAmountForBackDIO();
        dio.setUserId(NumberUtil.isNullOrZero(orderWork.getUserId())? null : orderWork.getUserId());
        dio.setBizType(orderWork.getBizType());
        dio.setChannelId(orderWork.getChannelId());
        dio.setCityId(orderWork.getCityId());
        dio.setInvoker(1);
        dio.setOrderAmount(orderWork.getOriginalAmount());
        dio.setOrderTime(orderWork.getReceiveTime());
        dio.setPlat(orderWork.getPlatWork());

        OrderProduct orderProduct = orderProductService.listOrderProductByOrderId(orderWork.getOrderId()).get(0);

        ProductInfoDIO productInfo = new ProductInfoDIO();
        productInfo.setBrandId(orderProduct.getBrandId());
        productInfo.setProductNum(orderProduct.getNumber());
        productInfo.setShowType(2);
        productInfo.setShowProductId(orderProduct.getShowProductId());
        productInfo.setProductId(orderProduct.getShowProductId());

        dio.setProductInfo(productInfo);

        Integer servItemType = orderWork.getServItemType();
        int tariff = (Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_FAULT) || Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) ? GlobalConsts.YES : GlobalConsts.NO;
        dio.setTariffOnoff(tariff);
        dio.setUntariffOnoff(tariff == GlobalConsts.YES ? GlobalConsts.NO : GlobalConsts.YES);

        dio.setExtendedWarranty(GlobalConsts.NO);
        dio.setUnExtendedWarranty(GlobalConsts.YES);

        dio.setOrderUsedCouponCodes(codeList);


        log.info("获取订单优惠 入参：{}", JSON.toJSONString(dio));
        ResponseDTO<OrderAmountForBackDRO> responseDTO = backOrderAmountRemoteService.getOrderDiscount(dio);
        log.info("获取订单优惠 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException(responseDTO.getMessage());
        }
        return responseDTO.getData();
    }

    private OrderAmountForBackDRO getBestDiscountByQuery(OrderWorkDiscountQuery query) throws OmsBaseException {
        log.info("----------------------{}", JSON.toJSONString(query));
        OrderAmountForBackDIO dio = new OrderAmountForBackDIO();
        dio.setBizType(query.getBizType());
        dio.setChannelId(query.getChannelId());
        dio.setCityId(query.getCityId());
        dio.setInvoker(1);
        dio.setOrderAmount(query.getPrice());
        dio.setOrderTime(DateUtil.getNow());
        dio.setPlat(query.getPlat());
        dio.setUserId(query.getUserId());

        if (StringUtil.isNotBlank(query.getBatchListJson())) {
            List<NewOrderDiscountDTO> batchList = JSON.parseArray(query.getBatchListJson(), NewOrderDiscountDTO.class);
            batchList.removeIf(item -> !Objects.equals(item.getSendCoupFlg(), GlobalConsts.YES));
            dio.setAdvanceBatchInfoDIOS(BeanMapper.mapList(batchList, AdvanceBatchInfoDIO.class));
        }

        ProductInfoDIO productInfo = new ProductInfoDIO();
        productInfo.setBrandId(query.getBrandId());
        productInfo.setProductNum(query.getProductNum());

        // 处理产品信息
        Integer showProductId = null;
        if (!Objects.equals(query.getShowType(), 2)) {
            // 获取对应的前台产品ID
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(query.getProductId()));
            defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            defaultEcProductQuery.setChannelId(query.getChannelId());
            defaultEcProductQuery.setBizType(query.getBizType());
            defaultEcProductQuery.setCityId(query.getCityId());
            ResponseDTO<List<ProductBaseDRO>> responseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            if (!CollectionUtils.isEmpty(responseDTO.getData())) {
                showProductId = responseDTO.getData().get(0).getProductId();
            } else {
                throw new OmsBaseException(String.format("后端产品[%s]未找到前端产品", query.getProductId()));
            }
        } else {
            showProductId = query.getProductId();
        }

        productInfo.setShowType(BaseProductConsts.EC_SHOW_TYPE);
        productInfo.setShowProductId(showProductId);
        dio.setProductInfo(productInfo);

        Integer servItemType = query.getServItemType();
        int tariff = (Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_FAULT) || Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) ? GlobalConsts.YES : GlobalConsts.NO;
        dio.setTariffOnoff(tariff);
        dio.setUntariffOnoff(tariff == GlobalConsts.YES ? GlobalConsts.NO : GlobalConsts.YES);

        dio.setExtendedWarranty(GlobalConsts.NO);
        dio.setUnExtendedWarranty(GlobalConsts.YES);

        log.info("获取订单优惠 入参：{}", JSON.toJSONString(dio));
        ResponseDTO<OrderAmountForBackDRO> responseDTO = backOrderAmountRemoteService.getOrderDiscount(dio);
        log.info("获取订单优惠 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException(responseDTO.getMessage());
        }
        return responseDTO.getData();
    }

}
